from rest_framework.viewsets import ViewSet
from rest_framework.viewsets import GenericViewSet
from api.extension.mixins import DigCreateModelMixin, DigListModelMixin, DigDestroyModelMixin, DigUpdateModelMixin
from api import models
from api.serializers import topic
from api.extension.filter import SelfFilterBackend
from django_filters import FilterSet, filters
from django_filters.rest_framework import DjangoFilterBackend


class TopicFilterSet(FilterSet):
    """配置显示更多数据的时候，不会加载加载过的，以小于当前页最小的id 的后面为数据"""
    # ?latest_id=99             ->  id<99
    # ?latest_id=99&limit=10    ->  id<99  limit 10
    latest_id = filters.NumberFilter(field_name='id', lookup_expr='lt')

    class Meta:
        model = models.Topic
        fields = ["latest_id", ]


class TopicView(ViewSet, DigCreateModelMixin, DigListModelMixin, DigDestroyModelMixin, DigUpdateModelMixin,
                GenericViewSet):
    filter_backends = [SelfFilterBackend,DjangoFilterBackend ] # 分页功能
    filterset_class = TopicFilterSet

    queryset = models.Topic.objects.filter(deleted=False).order_by('-id')
    serializer_class = topic.TopicSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    def perform_destroy(self, instance):
        instance.delete = True
        instance.save()
